var logged = false;
var loginNotice = '';

function showNotice(html) {
    document.getElementById("notice").innerHTML = html;
    document.getElementById("notice").style.display = "block";
}

function onAddResult(result) {
    console.log("add result: " + JSON.stringify(result));
    if (result.word == "" && result.query == "addSelectedWord" ) {
        showNotice("<span class='error'>no word selected!</span>");
        return;
    }
    if (!result.learnUrl) {
        showNotice( "<span class='error'>Add word '" + result.word + "' failed!</span>" );
        return;
    }
    showNotice("Word '" + result.word + "' added! <a href='" + result.learnUrl + "' target='_blank'>Learn it now!</a>");
}
function addWord(word) {
    waitForQuery();
    var shanbay = new ShanbayAPI();
    shanbay.addWord(
        word,
        function (result) {
            var message = new Object();
            message.word = word;
            if (result != null && result.id) {
                message.learnUrl = shanbay.getLearnWordUrl(result.id);
            }
            onAddResult(message);
        }
    );
}
function addInput() {
    if (!logged) {
        showNotice( loginNotice );
        return;
    }

    console.log("fire add input.");
    var word = document.getElementById("wordInput").value;
    if (word == "") {
        showNotice("<font color='red'>please input the word</font>");
        document.getElementById("wordInput").focus();
        return;
    }
	addWord(word);
}
function addSelected(word) {
	console.log("selected: " + word);
	if (word) {
		console.log("fire add input: " + word);
		addWord(word);
	}
}

function init() {
    var shanbay = new ShanbayAPI();
    loginNotice = '<span class="user">Please <a href="#" onclick="goURL(\'' + shanbay.getLoginURL() + '\')">login</a> first.</span>';

    shanbay.getUser(
    function (user) {
        console.log("get user: " + user);

        var welcomeMessage = "";
        if (!user) {
            logged = false;
            welcomeMessage = loginNotice;
        } else {
            logged = true;
            welcomeMessage = '<span class="user">Welcome back, <a href="#" onclick="goURL(\"' + shanbay.getUserURL(user) + '\")">' + user + '</a></span>';
        }
        var welcome = document.getElementById('welcome');
        welcome.innerHTML = welcomeMessage;
    }
    );
}

function goURL(url){
    window.open(url);
    window.self.close();
}

function waitForQuery(){
    var res = document.getElementById('notice');
    res.innerHTML = '<img src="img/icon_wait.gif">';
}
